/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gr.context;

import com.gr.analys.VietAnalyzer;
import com.gr.search.Connector;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.io.IOException;
import java.io.StringReader;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import vn.hus.nlp.tokenizer.tokens.TaggedWord;

/**
 *
 * @author Hieudt
 */
public class ContextController {
    private Profile profile;
    private History history;
    private QueryLog[] logList;
    private Map<String,Integer> interestList = new HashMap<>();
    private VietAnalyzer viA = new VietAnalyzer();
    
    public ContextController(int id){
        this.profile=new Profile(id);
    }
    
    public void gainLog() throws SQLException, ClassNotFoundException{
        Connection con = Connector.connect2();
        Statement s = (Statement) con.createStatement (); 
        s.executeQuery("SELECT user_id, query, date FROM log where user_id="+profile.getID()+" limit 25"); 
        ResultSet rs = s.getResultSet ();
        QueryLog[] logListt = new QueryLog[25];
        int i=0;
        while (rs.next ()){ 
           int idVal = rs.getInt ("user_id");                          // int idVal = rs.getInt (1); 
           String queryVal = rs.getString ("query");  // String nameVal = rs.getString (2); 
           Date dateVal = rs.getDate("date");
           //String urlsVal = rs.getString("urls");
           logListt[i] = new QueryLog(queryVal, idVal, dateVal);
           System.out.println(logListt[i].queryLogToString());
           //System.out.println ("ID" + idVal + "Ho v ten:"+nameVal); 
           i++;
        }
        logList = new QueryLog[i];
        for(int j=0;j<i;j++)
        logList[j]=logListt[j];
        rs.close ();
        //
        
        //
        s.close (); 
        con.close();
    }
public void updateHistory() throws IOException{
        //init
    if(logList.length>20){
        Map<TaggedWord, Integer> numberOfPosts = new HashMap<>();
        ValueComparator bvc =  new ValueComparator(numberOfPosts);
        TreeMap<TaggedWord,Integer> sorted_map = new TreeMap(bvc);
        
        StringBuilder buf;
        //add query term to map
        for(int i=0;i<logList.length;i++){
            ArrayList<TaggedWord> arr = viA.reusableTokenStream(new StringReader(logList[i].getQuery())).getList();
            for( TaggedWord w:arr){
                Integer count = numberOfPosts.get(w);
                numberOfPosts.put(w, count == null ? 1 : ++count);
            }
        }
       sorted_map.putAll(numberOfPosts);
       System.out.println(numberOfPosts.size()+"-"+sorted_map.size());
       System.out.println("unsorted map");
        for (TaggedWord key : numberOfPosts.keySet()) {
            System.out.println("key/value: " + key + "/"+numberOfPosts.get(key));
        }
        System.out.println(" hisroty results");
//        for (TaggedWord key : sorted_map.keySet()) {
//            System.out.println("key/value: " + key + "/"+sorted_map.get(key));
//        }
       Iterator iterator = sorted_map.entrySet().iterator();
        StringBuilder qbuf = new StringBuilder();
        int i=0;
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            System.out.println("key/value: " + entry.getKey() + "-"+entry.getKey().toString()+"/"+entry.getValue());
             if (i<3) qbuf.append("\"").append(entry.getKey()).append("\""+" ");
             i++;
             Integer boostVal = interestList.get(entry.getKey().toString());
             if(boostVal!=null) interestList.put(entry.getKey().toString(), boostVal+(int)entry.getValue());
//            int fre=(Integer)entry.getKey();
//            if free
//            scoreDoc4[i].doc=sd.doc;
//            scoreDoc4[i].score=sc.floatValue();
       
        }
         System.out.println("writing interest");
        updateInterest();
        System.out.println("writing history");            
        history = new History(logList[0].getUserID(),qbuf.toString());
        
        history.writeHistory();
    }   
    }
    public void loadUserInterest(){
        try {
           Connection connect = Connector.connect2();
           Statement s = (Statement) connect.createStatement (); 
           StringBuilder buf = new StringBuilder();
           s.executeQuery("SELECT term, boost FROM interest where user_id ="+profile.getID()+" order by boost ASC"); 
           ResultSet rs = s.getResultSet (); 
            while (rs.next ()){                         // int idVal = rs.getInt (1); 
           String termVal = rs.getString ("term");  // String nameVal = rs.getString (2); 
           int boostVal=rs.getInt("boost");
           interestList.put(termVal, boostVal);
           System.out.println ("Term: "+termVal+".\n");
          
           } 
//            updateInterest();
           rs.close (); 
           s.close (); 
           connect.close();
           System.out.println(buf.toString());
       } catch (ClassNotFoundException | SQLException e) {
           System.out.println("Connect Error [loadInterest-ContextController]!");
          
        
       }
    }
    public void updateInterest(){
        System.out.println("update interest");
        try
        {
            Connection con = Connector.connect2();
            java.sql.PreparedStatement stmt=con.prepareStatement("UPDATE interest SET boost = ? WHERE user_id=? AND term=?;");
            for (String key : interestList.keySet()) {
            System.out.println("key/value: " + key + "/"+interestList.get(key));
            stmt.setInt(1,(int)interestList.get(key));
            stmt.setInt(2,profile.getID());
            stmt.setString(3,key);
            //stmt.setString(3,URLs);
            stmt.executeUpdate();
            }
            con.close();
            System.out.println("update interest successfull");
        }
        catch (ClassNotFoundException ex) {
            Logger.getLogger(History.class.getName()).log(Level.SEVERE, null, ex);
        }catch(SQLException e)
        {
            System.err.println("Cant update interest!!!");
        }         
    }
    class ValueComparator implements Comparator {

      Map base;
      public ValueComparator(Map base) {
          this.base = base;
      }

            @Override
      public int compare(Object a, Object b) {

        if((Integer)base.get(a) < (Integer)base.get(b)) {
          return 1;
        } else if((Integer)base.get(a) == (Integer)base.get(b)) {
          return -1;
        } else {
          return -1;
        }
      }
    }
          public static void main(String[] args){ 
        try {
            ContextController cc = new ContextController(2);  
            cc.gainLog();
            cc.loadUserInterest();
            System.out.println("****print log list *********");
            for(QueryLog ql:cc.logList)
            if(ql.queryLogToString()!=null) System.out.println(ql.queryLogToString());
            else System.out.println("null");
            System.out.println("****print history map*********");
            cc.updateHistory();
        } catch (IOException | SQLException | ClassNotFoundException ex) {
            Logger.getLogger(ContextManager.class.getName()).log(Level.SEVERE, null, ex);
        }
          } 
}
